package com.android.hw.projectmenu;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.os.SystemProperties;

import com.android.internal.app.IBatteryStats;


public class UsbCharge extends Activity {
	final static String TAG="ProjectMenu/UsbCharge";
	
	final static String USB_CHARGE_PROP="persist.usb.chgdisabled";
	final static String CHARGE_ENABLE="0"; //允许充电
	final static String CHARGE_DISABLE="1";//禁止充电
	
	final static String POWER_CONTROL_PROP="persist.usb.power_ctrl";
	final static String POWER_CONTROL_FILE="/sys/class/power_supply/battery/hy_tst";
	
	final static String CHARGE_TYPE_FILE="/sys/class/power_supply/usb/type";
	private RadioGroup chargeGroup;
	private RadioGroup group;
	
		private static byte[][] pwr_value = {
						{'0'},         //不选择
						{'1','9','2'}, //200mA
						{'1','9','3'}, //450mA
						{'1','9','4'}, //600mA
						{'1','9','5'}, //900mA
						{'1','9','6'}, //1300mA
						{'1','9','7'}, //1500mA
						{'1','9','8'}, //1800mA
						};
		private int[] ids   = {
					R.id.radio0, 
					R.id.radio1, R.id.radio2, R.id.radio3,
					R.id.radio4, R.id.radio5, R.id.radio6, R.id.radio7
				};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usb_charge);

		group = (RadioGroup)this.findViewById(R.id.radioGroup1);
		group.setOnCheckedChangeListener(groupListener);
		
		chargeGroup = (RadioGroup)this.findViewById(R.id.radioGroup_charge);
		chargeGroup.setOnCheckedChangeListener(chargeListener);
		updateView();
		
		IntentFilter  mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        
	}
	
    @Override
    public void onDestroy() {
       // unregisterReceiver(mIntentReceiver);
        super.onDestroy();
       
    }
    
    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
            	updateView();
            }
        }
    };
    
	private void updateView(){
		Log.d(TAG,"updateView");
		if(isEnableCharge()){
			chargeGroup.check(R.id.enable_charge);
		}else{
			chargeGroup.check(R.id.disable_charge);
		}
		
		int ctrl=getPowerCtrl();
		if(isUsbCharge() && ctrl>=3){
			setPowerCtrl(0);
			ctrl = 0;
		}
		group.check(ids[ctrl]);
		
	};
	private OnCheckedChangeListener chargeListener = new OnCheckedChangeListener(){


		@Override
		public void onCheckedChanged(RadioGroup arg0, int arg1) {
			// TODO Auto-generated method stub
			Log.d(TAG,"chargeListener onCheckedChanged ");
			switch(arg1){
			case R.id.enable_charge:
				setCharge(true);
				break;
			case R.id.disable_charge:
				setCharge(false);
				break;					
			default:;
			}
		}
	};
	

	
	private OnCheckedChangeListener groupListener = new OnCheckedChangeListener() {
	
		@Override
		public void onCheckedChanged(RadioGroup arg0, int arg1) {
			// TODO Auto-generated method stub
			Log.d(TAG,"groupListener onCheckedChanged");
			for(int i=0; i < ids.length;i++){
				if(arg1 == ids[i]){
					Log.d(TAG,"button index="+i);
					if(isUsbCharge() && i >= 3){
						pupDialog();
					}else{
						setPowerCtrl(i);
					}
				}
			}
		}
		
	
	};
	/**
	 * Charge type is Usb or Ac ?
	 * @return
	 */
	private boolean isUsbCharge(){
		
		FileInputStream reader=null;
		byte[] type =  new byte[20];
		
		/*
		try {
			reader=new FileInputStream(CHARGE_TYPE_FILE);
			reader.read(type, 0, 20);
			reader.close();
			
			String log="";
			for(int i=0; i<10 ; i++){
				log=log+(int)type[i];
			}
			SystemProperties.set("persist.usb.plugtype", log);

			
			 } catch (IOException e) {
			    	e.printStackTrace();
			    	Log.e(TAG,"isUsbCharge : read failed");
			 } 
		*/
		
	
		try {
			reader=new FileInputStream(CHARGE_TYPE_FILE);
			reader.read(type, 0, 4);
			reader.close();
			
			if(type[0]=='U'&& type[1]=='S' && type[2]=='B'&& type[3]==10){
				Log.d(TAG,"isUsbCharge : true");
				return true;
			}
			
		 } catch (IOException e) {
		    	e.printStackTrace();
		    	Log.e(TAG,"isUsbCharge : read failed");
		 } 

	    
		Log.d(TAG,"isUsbCharge : false");
		return false;
	}
	
	/**
	 * 
	 */
	private int getPowerCtrl() {
		
		int choose =  SystemProperties.getInt(POWER_CONTROL_PROP, 0);
		
		Log.d(TAG,"getPowerCtrl : "+choose);
		return choose;
	}
	
	
	/**
	 * Control the current of charge 
	 * @param data
	 */
	private void setPowerCtrl(int i) {
		Log.d(TAG,"setPowerCtrl : "+i);
		byte[] data = pwr_value[i];
	    FileOutputStream ctrl=null;
	    
	    try {
			ctrl = new FileOutputStream(POWER_CONTROL_FILE);
			ctrl.write(data);
			ctrl.close();
			
			SystemProperties.set(POWER_CONTROL_PROP, ""+i);
	    } catch (IOException e) {
	    	e.printStackTrace();
	    	Log.e(TAG,"setPowerCtrl : write failed");
	    }
	    updateView();
	}
	
	/**
	 * 
	 */
	private void pupDialog(){
		 updateView();
		AlertDialog alertDialog = new AlertDialog.Builder(this). 
                setTitle(R.string.temp_ctrl). 
                setMessage(R.string.charge_warning). 
                setPositiveButton("OK", null).
                create(); 
        alertDialog.show(); 
        alertDialog.setOnDismissListener( new DialogInterface.OnDismissListener(){

			@Override
			public void onDismiss(DialogInterface arg0) {
				// TODO Auto-generated method stub
				
			}
        	
        });
	}
	/**
	 * 
	 * @return
	 */
	private boolean isEnableCharge(){
		String enable= SystemProperties.get(USB_CHARGE_PROP, CHARGE_ENABLE);
		Log.d(TAG,"isEnabeleCharge: "+enable);
		if(enable.equals(CHARGE_ENABLE)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 
	 * @param enable
	 */
	private void setCharge(boolean enable){
		Log.e(TAG,"setCharge : "+enable);
		if(enable){
			SystemProperties.set(USB_CHARGE_PROP, CHARGE_ENABLE);
		}else{
			SystemProperties.set(USB_CHARGE_PROP, CHARGE_DISABLE);
	
		}
		
		updateView();
	}


}